package com.example.homeworkmanagement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.homeworkmanagement.pojo.Attachments;
import com.example.homeworkmanagement.mapper.AttachmentsMapper;
import com.example.homeworkmanagement.service.AttachmentsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.homeworkmanagement.utils.DocxUtil;
import com.example.homeworkmanagement.vo.ResultVO;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 拒绝加班
 * @since 2025-05-25
 */
@Service
public class AttachmentsServiceImpl extends ServiceImpl<AttachmentsMapper, Attachments> implements AttachmentsService {

    @Override
    public ResultVO<Attachments> deleteAttachment(Integer attachmentId) {
        try {
            // 检查附件是否存在
            if (this.getOne(new QueryWrapper<Attachments>().eq("attachment",attachmentId))==null) {
                return ResultVO.fail("附件ID不存在");
            }
            boolean deleteSuccess = this.removeById(attachmentId);
            return deleteSuccess ?
                    ResultVO.success("附件删除成功") :
                    ResultVO.fail("附件删除失败");
        } catch (Exception e) {
            return ResultVO.fail("删除附件时发生异常：" + e.getMessage());
        }
    }

    @Override
    public ResultVO<String> downloadAttachmentByAttachmentId(Integer attachmentId) {
        try {
            // 1. 根据附件ID查询附件信息
            Attachments attachment = this.getById(attachmentId);
            if (attachment == null) {
                return ResultVO.fail("附件不存在");
            }

            // 2. 从附件信息中提取文件名和内容
            String filename = attachment.getFilename();
            String content = attachment.getContent();

            // 3. 生成DOCX文件（使用已有的generateDocx方法）
            // 提取原始文件名（不含扩展名）作为生成文件的基础名称
            String baseFilename = filename.substring(0, filename.lastIndexOf('.'));
            DocxUtil.generateDocx(baseFilename, content);

            // 4. 返回文件路径或下载链接
            String filePath = Paths.get(
                    System.getProperty("user.home"),
                    "Downloads",
                    DocxUtil.ensureDocxExtension(baseFilename)
            ).toString();

            return ResultVO.success("文件生成成功", filePath);

        } catch (IOException e) {
            return ResultVO.fail("文件生成失败，请重试");
        } catch (Exception e) {
            return ResultVO.fail("系统异常，请联系管理员");
        }
    }

}
